'use strict'
const path = require('path')
const glob = require('glob')
const setting = require('./src/setting')
function resolve (dir) {
  return path.join(__dirname, dir)
}
function getEntry (globPath, ignore) {
  let entries = {}
  let pageName
  const filePaths = glob.sync(globPath).filter(item => !/\.\w+$/.test(item))
  filePaths.forEach(entry => {
    pageName = entry.split('/').pop()
    entries[pageName] = {
      entry: `src/module/${pageName}/main.js`,
      template: 'public/index.html',
      title: setting.title,
      filename: `${pageName}.html`
    }
  })
  return entries
}
const pages = getEntry('./src/module/**?', '')

module.exports = {
  publicPath: '/',
  outputDir: 'dev',
  filenameHashing: true,
  productionSourceMap: false,
  configureWebpack: (config) => {
    if (process.env.NODE_ENV === 'production') {
    // 打包生成的文件
      config.output.filename = `[name]_${setting.timestamp}_v${setting.version}.js`
      config.output.chunkFilename = `[name]_${setting.timestamp}_v${setting.version}.js`
      // 将每个依赖包打包成单独的js文件
      const optimization = {
        runtimeChunk: 'single',
        splitChunks: {
          chunks: 'all',
          maxInitialRequests: Infinity,
          minSize: 20000,
          cacheGroups: {
            vendor: {
              test: /[\\/]node_modules[\\/]/,
              name (module) {
                const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1]
                return `npm_${packageName.replace('@', '')}`
              }
            }
          }
        }
      }
      Object.assign(config, { optimization })
    }
  },
  chainWebpack: config => {
    config.resolve.alias
      .set('@', resolve('src'))
      .set('home', resolve('src/module/home'))
  },
  pages: pages,
  devServer: {
    open: false,
    host: '0.0.0.0',
    port: 8080,
    https: false,
    hot: true,
    hotOnly: false,
    overlay: {
      warnings: true,
      errors: true
    },
    proxy: {
      '/api': {
        target: 'http://',
        changeOrigin: true,
        pathRewrite: {
          '^/api': '/api'
        }
      }
    }
  }
}
